package com.xiatl.cgi.server.cgi.filter;


import com.alibaba.fastjson.JSONObject;
import com.xiatl.cgi.server.cgi.CgiDataModel;
import com.xiatl.cgi.server.cgi.CgiHandler;
import com.xiatl.cgi.server.cgi.code.RespCode;
import com.xiatl.cgi.server.cgi.exception.CgiException;
import com.xiatl.cgi.server.cgi.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 接口验证拦截过滤器
 */
@Order(1)
@WebFilter(urlPatterns = {"/server/*"})
public class CgiFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(CgiFilter.class);
    @Autowired
    private CgiHandler cgiHandler;

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        ServletRequest requestWrapper = null;
        if (servletRequest != null) {
            // 获取请求参数（必须要做一下，因为请求参数拿一次就没了，获取后需要回写到request里）
            NewHttpRequestWrapper newHttpRequestWrapper = new NewHttpRequestWrapper((HttpServletRequest) servletRequest);
            CgiDataModel cgiDataModel = new CgiDataModel();
            cgiDataModel.setPath(request.getRequestURI());
            cgiDataModel.setAppKey(request.getHeader("appKey"));
            cgiDataModel.setSign(request.getHeader("sign"));
            cgiDataModel.setTimestamp(request.getHeader("timestamp"));
            String body = newHttpRequestWrapper.getBody();
            logger.info("外部接口请求入参：{}", body);
            if (!StringUtils.isEmpty(body)) {
                cgiDataModel.setParams(JSONObject.parseObject(body));
            }
            try {
                // 过滤器处理
                this.cgiHandler.doHandle(cgiDataModel);
            } catch (CgiException e) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(ResultUtil.resError(e.getMessage(), e.getErrorCode()).toString());
                return;
            } catch (Exception e) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(ResultUtil.resError("验签异常。" + e.getMessage(), RespCode.ERROR).toString());
                return;
            }
            // 重写进ServletRequest
            requestWrapper = newHttpRequestWrapper;
        }
        if (requestWrapper == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }

}
